In Svelte, stores are reactive objects that notify subscribers when their values change. If subscribers are not properly cleaned up, memory leaks can occur. This is especially important for custom stores, readable stores with side effects, or stores used in components that are frequently mounted and destroyed.
When creating a readable store, the setup function can return a cleanup function that will be called when the last subscriber unsubscribes. This ensures that intervals, subscriptions, or other side effects are properly cleared.
When you manually subscribe to a store in a component, always unsubscribe when the component is destroyed to prevent memory leaks.
Using the $store syntax in Svelte components automatically subscribes and unsubscribes when the component is mounted and destroyed, reducing the risk of memory leaks.
If your custom store uses timers, websockets, or other resources, make sure to stop or unsubscribe from them when there are no subscribers.
Always provide a cleanup function for readable stores with side effects.
Unsubscribe from manually subscribed stores in onDestroy.
Use $store auto-subscription syntax whenever possible.
Clean up resources like timers, intervals, and websockets in custom stores when no subscribers remain.